package com.sfx.算法专题.链表.合并链表;

import com.sfx.算法专题.链表.公共结点.Code_1_getIntersectionNode;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-07-30
 * Time: 14:14
 */
public class Code_1_mergeTwoLists {
    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }
    static class Solution1 {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if(l1 == null) return l2;
            if(l2 == null) return l1;
            if(l1.val < l2.val) {
                l1.next = mergeTwoLists(l1.next,l2);
                return l1;
            }else{
                l2.next = mergeTwoLists(l1,l2.next);
                return l2;
            }
        }
    }
    class Solution2 {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            if(l1 == null) return l2;
            if(l2 == null) return l1;
            ListNode head = null;
            ListNode tmp = null;
            if(l1.val < l2.val) {
                head = tmp = l1;
                l1 = l1.next;
            }else {
                head = tmp = l2;
                l2 = l2.next;
            }
            while(l1!=null && l2!=null) {
                if(l1.val > l2.val) {
                    tmp.next = l2;
                    l2 = l2.next;
                }else {
                    tmp.next = l1;
                    l1 = l1.next;
                }
                tmp = tmp.next;
            }
            tmp.next = l1==null ? l2 : l1;
            return head;
        }
    }
    class Solution3 {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            ListNode dummy = new ListNode(-1);
            ListNode tmp = dummy;
            if(l1 == null) return l2;
            if(l2 == null) return l1;
            while(l1!=null && l2!=null) {
                if(l1.val > l2.val) {
                    tmp.next = l2;
                    l2 = l2.next;
                }else {
                    tmp.next = l1;
                    l1 = l1.next;
                }
                tmp = tmp.next;
            }
            if(l1==null) tmp.next = l2;
            else tmp.next = l1;
            return dummy.next;
        }
    }
}